package com.usian.skill.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.skill.mapper.SkillGoodsMapper;
import com.usian.skill.pojo.OrderInfo;
import com.usian.skill.pojo.SkillOrder;
import com.usian.skill.service.OrderInfoService;
import com.usian.skill.service.SkillOrderService;
import com.usian.skill.service.SkillService;
import com.usian.skill.util.MD5Util;
import com.usian.skill.util.UUIDUtil;
import com.usian.skill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * ClassName: SkillServiceImpl
 * Author:   WGG
 * Date:    2022-12-2022/12/12-16:52
 * Version: 1.0
 * Description:
 */
@Service
public class SkillServiceImpl implements SkillService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Resource
    private SkillGoodsMapper skillGoodsMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SkillOrderService skillOrderService;

    public OrderInfo skill(Long userId, GoodsVo goodsVo){
        //减库存
        int i = skillGoodsMapper.updateSkillGoods(goodsVo.getId());
        if (i>0){
            //生成订单
            return orderInfoService.add(userId,goodsVo);
        }else {
            //扣减库存失败，在redis中做标记
            stringRedisTemplate.opsForValue().set("result"+goodsVo.getId(),true+"");
        }
        return null;
    }

    @Override
    public long getSkillResult(String userId, long goodsId) {
        //去skill_order表中查询秒杀的订单
        SkillOrder skillOrder = skillOrderService.getOne(Wrappers.<SkillOrder>lambdaQuery().eq(SkillOrder::getGoodsId, goodsId).eq(SkillOrder::getUserId, userId));
        if (skillOrder!=null){
            return skillOrder.getOrderId();
        }else {
            String isOver = stringRedisTemplate.opsForValue().get("result" + goodsId);
            if (Boolean.parseBoolean(isOver)) {
                return -1; //秒杀失败
            }else {
                return 0; //排队中
            }
        }
    }

    //将随机生成的数据保存在redis中
    @Override
    public String createMiaoShaPath(String userId, long goodsId) {
        //生成的随机数
        String str = MD5Util.md5(UUIDUtil.uuid()+"666");
        //随机数保存在redis中
        stringRedisTemplate.opsForValue().set(userId+"random"+goodsId,str);
        return str;
    }

    //检测redis中的随机数是否和页面的一致
    @Override
    public boolean checkPath(String userId, long goodsId, String path) {
        //从redis中获取数据
        String random = stringRedisTemplate.opsForValue().get(userId + "random" + goodsId);
        return random.equals(path);
    }

    @Override
    public BufferedImage createVerifyCode(String user, long goodsId) {
        //GUI
        if(user == null || goodsId <=0) {
            return null;
        }
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中  计算对应的结果
        int rnd = calc(verifyCode);
        stringRedisTemplate.opsForValue().set("VerifyCode"+user+goodsId, rnd+"");
        //输出图片
        return image;
    }

    @Override
    public boolean checkVerifyCode(String user, long goodsId, int verifyCode) {
        if(user == null || goodsId <=0) {
            return false;
        }
        Integer codeOld = Integer.parseInt(stringRedisTemplate.opsForValue().get("VerifyCode"+user+goodsId));
        if(codeOld == null || codeOld - verifyCode != 0 ) {
            return false;
        }
        stringRedisTemplate.delete(stringRedisTemplate.opsForValue().get("VerifyCode"+user+goodsId));
        return true;
    }
    //计算图形上的结果
    private static int calc(String exp) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (Integer)engine.eval(exp);
        }catch(Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    private static char[] ops = new char[] {'+', '-', '*'};
    /**
     * + - *
     * */
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = ""+ num1 + op1 + num2 + op2 + num3;
        return exp;
    }

}
